package Leetcode第一期;

import java.util.HashMap;
import java.util.Stack;

public class 有效的括号_20 {
    // Hash table that takes care of the mappings.
    private HashMap<Character, Character> mappings;

    // Initialize hash map with mappings. This simply makes the code easier to read.
    public 有效的括号_20() {
        this.mappings = new HashMap<Character, Character>();
        this.mappings.put(')', '(');
        this.mappings.put('}', '{');
        this.mappings.put(']', '[');
    }
    public boolean isValid(String s) {
        Stack<Character> stack=new Stack<Character>();
        for(int i=0;i<s.length();i++){
            char ch=s.charAt(i);
            if(this.mappings.containsKey(ch)){
                char topElement= stack.isEmpty()?'#':stack.pop();
                if(topElement!=this.mappings.get(ch)){
                    return false;
                }
            }else{
                stack.push(ch);
            }

        }
        return stack.isEmpty();
    }

    public boolean isValidA(String s) {
        Stack<Character> stack=new Stack<Character>();
        stack.push(s.charAt(0));
        for (int i=1;i<s.length();i++){
            char c=s.charAt(i);
            if (stack.isEmpty()){
                stack.push(c);
            }else {
                if (stack.peek().equals(mappings.get(c))){
                    stack.pop();
                }else {
                    stack.push(c);
                }
            }
        }
        return stack.isEmpty();
    }

    public static void main(String[] args) {
        String s="(()())";
        System.out.println(new 有效的括号_20().isValidA(s));
    }


}
